<?php
namespace app\home\controller;
use mysql_xdevapi\Expression;
use think\Controller;
use think\Cookie;
use think\Db;
use think\Request;
/*
 * 权限代码
 * 4:系统管理员
 * 3：资产管理员
 * 2：实验室主任
 * 1：实验员
 * 0：授权用户
*/
class Machine extends Controller
{
    ////////////////////私有类/////////////////
    function excel_to_array($file,$from_row,$from_col,$to_col)   //将excel中的数据转换成数组
    {
        $file_type='xlsx';
        if($file_type=='xlsx'){
            $reader = \PHPExcel_IOFactory::createReader('Excel2007');
        }else{
            $reader=\PHPExcel_IOFactory::createReader('Excel5');
        }

        $excel = $reader->load($file,$encode = 'utf-8');
        //读取第一张表
        $sheet = $excel->getSheet(0);
        //获取总行数
        $row_num = $sheet->getHighestRow();
        $col_num=$to_col;

        //获取总列数
        $row=0;
        $data = array(); //数组形式获取表格数据$
        for ($i = $from_row; $i <= (int)$row_num; $i ++) {
            $col=0;
            for($j=$from_col-1;$j<=(int)$col_num-1;$j++){
                $data[$row][$col]  = $sheet->getCellByColumnAndRow($j,$i)->getValue();
                $col++;
            }
            $row++;
            //将数据保存到数据库
        }
        return $data;
    }
    function authid_to_name($authority)   //用户权限id转权限名字
    {
        switch ($authority){
            case 4:
                return '系统管理员';
                break;
            case 3:
                return '资产管理员';
                break;
            case 2:
                return '实验室主任';
                break;
            case 1:
                return '实验员';
                break;
            case 0:
                return '授权用户';
                break;
        }
    }
    function authority($array){
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        $user_data=Db::name('user')->where('safecode',$safecode)->find();
        $authority_id=$user_data['authority'];
        if(!in_array($authority_id,$array)){
            $this->error('无权访问','../Index/home');
            exit();
        }
    }
    function get_this_data()    //获取当前用户信息
    {
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        return Db::name('user')->where('safecode',$safecode)->find();
    }
    public function export_machine_data()     //导出设备信息
    {
        $this->authority([4,3,2,1,0]);
        $machine = Db::name('machine');
        $list = $machine->select();
        $objPHPExcel = new \PHPExcel();
        // 设置sheet
        $objPHPExcel->setActiveSheetIndex(0);
        // 设置列的宽度
        $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(25);
        $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(20);
        $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(40);

        // 设置表头
        $objPHPExcel->getActiveSheet()->SetCellValue('A1', '设备编号');
        $objPHPExcel->getActiveSheet()->SetCellValue('B1', '设备名称');
        $objPHPExcel->getActiveSheet()->SetCellValue('C1', '单价');
        $objPHPExcel->getActiveSheet()->SetCellValue('D1', '管理人');
        $objPHPExcel->getActiveSheet()->SetCellValue('E1', '存放位置');
        $objPHPExcel->getActiveSheet()->SetCellValue('F1', '型号');
        $objPHPExcel->getActiveSheet()->SetCellValue('G1', '规格');
        $objPHPExcel->getActiveSheet()->SetCellValue('H1', '购置时间');
        $objPHPExcel->getActiveSheet()->SetCellValue('I1', '状态');
        $objPHPExcel->getActiveSheet()->SetCellValue('J1', '备注');
        //存取数据
        $num = 2;
        foreach ($list as $k => $v) {
            $objPHPExcel->getActiveSheet()->SetCellValue('A' . $num, $v['asset_id']);
            $objPHPExcel->getActiveSheet()->SetCellValue('B' . $num, $v['asset_name']);
            $objPHPExcel->getActiveSheet()->SetCellValue('C' . $num, $v['unit_price']);
            $objPHPExcel->getActiveSheet()->SetCellValue('D' . $num, $v['manager']);
            $objPHPExcel->getActiveSheet()->SetCellValue('E' . $num, $v['depositary']);
            $objPHPExcel->getActiveSheet()->SetCellValue('F' . $num, $v['model']);
            $objPHPExcel->getActiveSheet()->SetCellValue('G' . $num, $v['standard']);
            $objPHPExcel->getActiveSheet()->SetCellValue('H' . $num, $v['time']);
            $objPHPExcel->getActiveSheet()->SetCellValue('I' . $num, $v['status']);
            $objPHPExcel->getActiveSheet()->SetCellValue('J' . $num, $v['comment']);
            $num++;
        }
        // 文件名称
        $fileName = "设备信息" . date('Y-m-d', time()) . rand(1, 1000);
        $xlsName = iconv('utf-8', 'gb2312', $fileName);
        // 设置工作表名
        $objPHPExcel->getActiveSheet()->setTitle('sheet');
        //下载 excel5与excel2007
        $objWriter = new \PHPExcel_Writer_Excel2007($objPHPExcel);
        ob_end_clean();     // 清除缓冲区,避免乱码
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control:must-revalidate,post-check=0,pre-check=0");
        header("Content-Type:application/force-download");
        header("Content-Type:application/vnd.ms-execl;charset=UTF-8");
        header("Content-Type:application/octet-stream");
        header("Content-Type:application/download");
        header("Content-Disposition:attachment;filename=" . $xlsName . ".xlsx");
        header("Content-Transfer-Encoding:binary");
        $objWriter->save("php://output");

    }
    public function machine()  //设备管理 权限4,3,2,1,0
    {
        $this->authority([4,3,2,1,0]);
        $cookie=new Cookie();
        $safecode=$cookie->get('safecode');
        $user_data=Db::name('user')->where('safecode',$safecode)->find();
        $this->assign('user',$user_data);
        return $this->fetch('machine',[],['__PUBLIC__'=>'/public/static']);
    }
    public function machine_json()  //  设备信息的json数据
    {
        $this->authority([4,3,2,1,0]);
        if(input('get.')){
            $filed=input('get.field');
            if($filed=='date'){
                if(input('get.from_date')&&input('get.to_date')){
                    $from_date=input('get.from_date');
                    $to_date=input('get.to_date');
                    $machine_data=Db::name('machine')->whereTime('time','between',[$from_date,$to_date])->select();
                }elseif (input('get.from_date')&&!input('get.to_date')){
                    $from_date=input('get.from_date');
                    $machine_data=Db::name('machine')->whereTime('time','>=',$from_date)->select();
                }elseif (!input('get.from_date')&&input('get.to_date')){
                    $to_date=input('get.to_date');
                    $machine_data=Db::name('machine')->whereTime('time','<=',$to_date)->select();
                }
            }else{
                $content=input('get.content');
                $machine_data=Db::name('machine')->where($filed,'like','%'.$content.'%')->order('time','desc')->select();
            }
        }else{
            $user_data=$this->get_this_data();
            $lab=$user_data['auth_lab'];
            $machine_data_a=Db::name('machine')->where('depositary',$lab)->select();
            $machine_data_b=Db::name('machine')->where('depositary','<>',$lab)->select();
            $machine_data=array_merge($machine_data_a,$machine_data_b);
        }

        return json($machine_data);
    }
    public function add_all()   //批量增加设备
    {
        return $this->fetch('add_all_machine',[],['__PUBLIC__'=>'/public/static']);

    }
    public function add_all_machine()   //批量增加设备
    {
        $this->authority([4,3]);
        $re=new Request();
        $files=$re->file('file_data');
        if($files){
            $info=$files->validate(['ext'=>'xlsx,xls'])->move('upload');
            if($info){
                $dir='upload/'.$info->getSaveName();
                $datas=$this->excel_to_array($dir,3,1,14);
                $success=0;
                $error=0;
                foreach ($datas as $data){
                    $arr=array();
                    $arr['asset_id']=$data[0];
                    $arr['asset_name']=$data[1];
                    $arr['unit_price']=$data[2];
                    $arr['manager']=$data[5];
                    $arr['depositary']=$data[6];
                    $arr['model']=$data[7];
                    $arr['standard']=$data[8];
                    $arr['time']=$data[9];
                    $arr['status']=$data[10];
                    $arr['comment']=$data[11];
                    try{
                        Db::name('machine')->insert($arr);
                        $success++;
                    }catch (\Exception $e) {
                        $error++;
                    }
                }
                return json(['success_num'=>$success,'error_num'=>$error]);
            }else{
                return json($info->getError());
            }
        }

    }
    public function add_machine()   //增加设备 权限：4，3
    {
        $this->authority([4,3]);
        if(input('post.')){
            $input_data=input('post.');
            $is_exist=Db::name('machine')->where('inside_id','=',$input_data['inside_id'])->whereOr('asset_id','=',$input_data['asset_id'])->find();
            if(!empty($is_exist)){
                $this->assign('msg','新增失败,编号存在');
                $this->assign('url','add_machine.html');
                return $this->fetch('do_error',[],['__PUBLIC__'=>'/public/static']);
            }
            if(Db::name('machine')->insert([
                'asset_id'=>$input_data['asset_id'],
                'inside_id'=>$input_data['inside_id'],
                'asset_name'=>$input_data['asset_name'],
                'unit_price'=>$input_data['unit_price'],
                'manager'=>$input_data['manager'],
                'depositary'=>$input_data['depositary'],
                'model'=>$input_data['model'],
                'standard'=>$input_data['standard'],
                'time'=>$input_data['time'],
                'status'=>$input_data['status'],
                'comment'=>$input_data['comment']
            ])){
                $this->assign('msg','新增成功');
                $this->assign('url','add_machine.html');
                return $this->fetch('do_success',[],['__PUBLIC__'=>'/public/static']);
            }else{
                $this->assign('msg','新增失败');
                $this->assign('url','add_machine.html');
                return $this->fetch('do_error',[],['__PUBLIC__'=>'/public/static']);
            }
        }
        return $this->fetch('machine_add',[],['__PUBLIC__'=>'/public/static']);
    }
    public function edit_machine()  // 设备编辑 权限：4，3，1
    {
        $this->authority([4,3,1]);
        if(input('get.')){
            $asset_id=input('get.asset_id');
            if(input('post.')){
                $unit_price=input('post.unit_price');
                $manager=input('post.manager');
                $depositary=input('post.depositary');
                $comment=input('post.comment');
                $status=input('post.status');
                if(Db::name('machine')->where('asset_id',$asset_id)->update([
                    'unit_price'=>$unit_price,
                    'manager'=>$manager,
                    'depositary'=>$depositary,
                    'comment'=>$comment,
                    'status'=>$status
                ])){
                    $this->assign('msg','修改成功');
                    $this->assign('url','edit_machine.html');
                    return $this->fetch('do_success',[],['__PUBLIC__'=>'/public/static']);
                }else{
                    $this->assign('msg','修改失败');
                    $this->assign('url','edit_machine.html');
                    return $this->fetch('do_success',[],['__PUBLIC__'=>'/public/static']);
                }
            }
            $machine_data=Db::name('machine')->where('asset_id',$asset_id)->find();
            $user_data=$this->get_this_data();
            if($user_data['authority']==1){
                if($user_data['auth_lab']!=$machine_data['depositary']){
                    $this->error('这不是你所管辖的设备');
                }
            }
            $this->assign('machine',$machine_data);
            return $this->fetch('machine_edit',[],['__PUBLIC__'=>'/public/static']);
        }else{
            $this->error('非法访问');
        }
    }
    public function look_machine() //设备信息查询 权限：4,3,2,1,0
    {
        $this->authority([4,3,2,1,0]);
        if(input('get.')){
            $asset_id=input('get.asset_id');
            $machine_data=Db::name('machine')->where('asset_id',$asset_id)->find();
            $this->assign('machine',$machine_data);
            return $this->fetch('machine_look',[],['__PUBLIC__'=>'/public/static']);
        }else{
            $this->error('非法请求');
        }
    }
    public function delete_machine() //设备删除  权限：4,3
    {
        $this->authority([4,3]);
        if(input('get.do')=='delete'){
            $in_data=file_get_contents('php://input');
            $data=json_decode($in_data,true);
            $arr=array();
            foreach ($data as $one){
                $arr[]=$one['asset_id'];
            }
            $arr2=[
                'msg'=>'success',
            ];
            if(Db::name('machine')->delete($arr)){
                return json($arr2);
            }
        }

    }
}
